package cn.sskxyz.security.core.config;

import cn.sskxyz.security.core.property.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStore;

/**
 * 资源服务通过jwkSetUri来验证token是否合法,类型需要配置为jwk,仅资源服务可以使用该类，认证服务需要使用 JwtTokenConfigure
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
@ConditionalOnProperty(prefix = "system.security", name = "token-type", havingValue = "jwk")
public class JwksTokenConfigure {

    @Autowired
    private SecurityProperties securityProperties;

    @Bean
    @ConditionalOnMissingBean(TokenStore.class)
    public TokenStore jwkTokenStore(){
        JwkTokenStore tokenStore = new JwkTokenStore(securityProperties.getJwkSetUri());
        return tokenStore;
    }

    @Bean
    @ConditionalOnMissingBean(DefaultTokenServices.class)
    public DefaultTokenServices tokenService() throws Exception {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(jwkTokenStore());
        tokenServices.afterPropertiesSet();
        return tokenServices;
    }
}
